# -*- coding:utf-8 -*-
# 网易云音乐的js逆向
import requests
import execjs          # 通过python代码去执行js代码
import os


class MusicData(object):
    def __init__(self):
        # 获取歌曲的名称和id
        self.music_data_url = "https://music.163.com/weapi/cloudsearch/get/web?csrf_token="
        # 获取歌曲的地址
        self.music_url = "https://music.163.com/weapi/song/enhance/player/url/v1?csrf_token="
        self.headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36"
        }
        if not os.path.exists("music"):
            os.mkdir("music")


    def get_music_data(self):
        data = {
            "params": "F6X4lsJ+ZmoJV/AgpiQc9ZseGEPl3Wh/sEUnxgEiyMqcFYv9bkdKGEqhfxfZoL6GMvmZ7ecNb2Y4IFc2gfjm/3QsVNYhinz0EcHjS8STEPMz53F+uk1l8tiPil2kKa3CTxdWDST2ZItuzM25Ak63vTSJnBM17J/Ukum/5ffKgaPs20TGST4LuhTXLUHx2mL9ybFDiQuvyhEZMnEtersIGa/kwyvhz5CrfBt6jLwPFCpHnug5Ckbmg4umRS+I0k3c/MMg9TvlaiN/PYsDXw7fLw==",
            "encSecKey": "72319e3e0e860e39af86179765514fe256945619f6ff9f04fb12984b87b7f1c47b345bc0211489a0235dd2fdc3a86595653b8d869c86008f4f5d501f2d440088c00d85e60b0a3ca179b55fd74bf3b9fee8e6fb08746b3251a1cb497cdd3e1acdeeb93f178a4ceaada30d9618faac3b5797820a9a640b87604594e744bfb0cb74"
        }
        response = requests.post(url=self.music_data_url, data=data, headers=self.headers)
        dict_data = response.json()["result"]["songs"]
        for data in dict_data:
            name = data["name"]
            music_id = data["id"]
            self.get_music_url_data(music_id=music_id, name=name)

    # 通过js逆向得到每首歌曲的表单信息(代码核心)
    def get_music_url_data(self, music_id, name):
        content = open("music.js", "r", encoding="utf-8").read()
        data_js = execjs.compile(content, cwd=r"C:\Users\34957\AppData\Roaming\npm\node_modules")
        bKC6w = data_js.call("music_data", music_id)
        data = {
            "params" : bKC6w["encText"],
            "encSecKey" : bKC6w["encSecKey"]
        }

        # 向歌曲地址发起请求
        response = requests.post(self.music_url, data=data, headers=self.headers)
        music_url = response.json()["data"][0]["url"]
        self.write_data(name=name, music_url=music_url)

    # 保存歌曲
    def write_data(self, name, music_url):
        try:
            with open("./music/" + name + ".mp3", "wb")as file:
                resp = requests.get(music_url).content
                file.write(resp)
                print(f"{name} -- 保存成功")
        except:
            print(f"{name} -- 是付费歌曲")

    def main(self):
        self.get_music_data()


if __name__ == '__main__':
    spider = MusicData()
    spider.main()
